<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */

class b2c_mdl_member_advance extends dbeav_model{
    var $return_array = array(); // 返回带有MAC地址的字串数组
    var $mac_addr;
    /**
     * check_account 预存款检查
     *
     * @param mixed $member_id
     * @param mixed $errMsg
     * @param mixed $money
     * @access public
     * @return bool
     */
    function check_account($member_id,&$errMsg,$money){
        $objMember = $this->app->model('members');
        $row= $objMember->dump($member_id,'advance');
        if($row){
            if($row['advance']['total']<0){
                  $errMsg.=app::get('b2c')->_('余额>0,禁止更新');
                  return false;   
               }
            if(count($row)>0){
                if($money > $row['advance']){
                     
                    $errMsg .= app::get('b2c')->_('预存款帐户余额不足');
                    return 0;
                }else{
                    return $row;
                }
            }else{
                $errMsg .= app::get('b2c')->_('预存款帐户不存在');
                return false;
            }
        }else{
            $errMsg .= app::get('b2c')->_('查询预存款帐户失败');
            return false;
        }
    }
    /**
     * add 预存款充值
     *
     * @param mixed $member_id
     * @param mixed $money
     * @param mixed $message
     * @access public
     * @return void
     */
    //by zhangyan 2015-10-28 添加账户bank_name   这里是审核
    function add($member_id,$money,$advance_type,$message,&$errMsg, $payment_id='', $order_id='' ,$paymenthod,$memo='',$type=0,$is_frontend=true,$bank_name=''){
       if(!$member_id){
            $errMsg .= app::get('b2c')->_('更新预存款账户失败');
            return false;
       }
        if($money){
            $adjmember = &$this->app->model('members');
            $advance = $this->get($member_id);
            if($advance < 0){
                $errMsg .= app::get('b2c')->_('更新预存款账户失败');
                return false;
            }
            #$total = $advance + $money;
            #$member['advance'] = $total;
            #$result = $adjmember->update($member,array('member_id'=>$member_id));
            $result = $adjmember->db->exec('UPDATE sdb_b2c_members SET advance = advance+'.$money.' where member_id='.$member_id);
            $member_advance = $this->get($member_id);
            //取得现有预存款
            $current_shop_advance = $this->get_shop_advance();
            $shop_advance = $current_shop_advance+$money;
            //取得ip
            $member_ip = base_request::get_remote_addr();
            //获得mac地址
            $member_mac= $this->GetMacAddr(PHP_OS);
            $data = array(
                    'member_id'=>$member_id,
                    'money'=>$money,
                    'advance_type'=>$advance_type,
                    'bank_name'=>$bank_name,
                    'message'=>$message,
                    'mtime'=>time(),
                    'payment_id'=>$payment_id,
                    'order_id'=>$order_id,
                    'paymethod'=>$paymenthod,
                    'memo'=>$memo,
                    'import_money'=>$money,
                    'explode_money'=>0,
                    'member_advance'=>$member_advance,
                    'shop_advance'=>$shop_advance,
                    'member_ip'=>$member_ip,
                    'member_mac'=>$member_mac,
            );
            //by zhangyan 收款同步到进销存，然后保存本地
            //如果是线上支付则不需要同步，只有ec后台增加或减少才会需要,如果类型为信用额则不需要同步
            if ($advance_type == '1') {
                $params = array(
                    'member_id'=>$member_id,
                    'money'=>$money,
                    'advance_type'=>$advance_type,
                    'bank_name'=>$bank_name,
                    'mtime'=>date("Y-m-d", time()),
                    'payment_id'=>$payment_id,
                    'order_id'=>$order_id,
                    'paymethod'=>$paymenthod,
                    'memo'=>$memo,
                );
                //2015-9-16 by 张艳,在保存前，先同步到jxc,同步成功后才保存到本地
                $obj_order_create = kernel::single("b2c_order_pay");
                $r=$obj_order_create->_get_data_pay($params);

                if($r['rsp']===false) {
                    // $this->end(false, $r['data']['msg']);
                    $msg = app::get('ectools')->_('支付单生成失败！'.$r['data']['msg']);
                    return false;
                }
            }
            if($this->save($data)){
                if (!$type){
                    $data['member_id']=$member_id;
                }

				/** 监听预存款变化 **/
				foreach(kernel::servicelist('member_advance_listener') as $service)
				{
					$arr_params = array(
						'member_id'=>$member_id,
						'doadd'=>true,
						'is_frontend'=>($is_frontend) ? true : false,
					);
					$service->listener_advance($arr_params);
				}
                return true;
            }else{
                $errMsg .= app::get('b2c')->_('更新预存款帐户失败');
                return false;
            }
        }else{
            $errMsg .= app::get('b2c')->_('更新预存款帐户失败');
            return false;
        }
    }


    /**
     * deduct 扣除预存款
     *
     * @param mixed $member_id
     * @param mixed $money
     * @param mixed $message
     * @access public
     * @return void
     */
    // by zhangyan 函数参数少传了$advance_type参数,添加bank_name
    function deduct($member_id,$money,$advance_type,$message,&$errMsg, $payment_id='', $order_id='' ,$paymethod,$memo='',$is_frontend=true,$bank_name=''){
        if(!$member_id){
            $errMsg .= app::get('b2c')->_('更新预存款账户失败');
            return false;
       }

       //检查预存款余额够不够
        if($row = $this->check_account($member_id,$errMsg,$money)){
           

            $advance = $this->app->model('members');
             //取得现有预存款
            $member_advance = $this->get($member_id);
            $data['member_id'] = $member_id;
            //判断充值额度（为负数）大于可用额度禁止通过审核 by wang 2017/12/11
            if($member_advance<$money){
                $errMsg.=app::get('b2c')->_('更新预存款账户失败');
                return false;
            }
            // $adjmember->db->exec('UPDATE sdb_b2c_members SET advance = advance-'.$money.' where member_id='.$member_id.' and advance >='.$money);
             //查询会员用户表
             $advance->db->exec('UPDATE sdb_b2c_members SET advance=advance-'.$money.' where member_id='.$member_id);
            $flag = $advance->db->affect_row();
            //var_dump($adjmember);return false;
            //2017-12-15 by jeff,修改后取得当前余额
            $member_advance = $this->get($member_id);
            if($flag){
                    if($member_advance < 0 || (!$flag && $money!=0)){
                    $errMsg .= app::get('b2c')->_('更新预存款账户失败');
                    return false;
                   }         
                 }
            

            //在$money=0的情况下，虽然sql执行成功了但是affect_row会返回false
           
            $current_shop_advance = $this->get_shop_advance();
            $shop_advance = $current_shop_advance-$money;
            //取得ip
            $member_ip = base_request::get_remote_addr();
            //获得mac地址
            $member_mac= $this->GetMacAddr(PHP_OS);
            if($shop_advance <0){
                $errMsg .= app::get('b2c')->_('更新预存款账户失败');
                return false;
            }
            $data = array(
                    'member_id'=>$member_id,
                    'money'=>$money,
                    'advance_type'=>$advance_type,
                    'bank_name'=>$bank_name,
                    'message'=>$message,
                    'mtime'=>time(),
                    'payment_id'=>$payment_id,
                    'order_id'=>$order_id,
                    'paymethod'=>$paymethod,
                    'memo'=>$memo,
                    'import_money'=>0,
                    'explode_money'=>$money,
                    'member_advance'=>$member_advance,
                    'shop_advance'=>$shop_advance,
                    'member_ip'=>$member_ip,
                    'member_mac'=>$member_mac,
            );
            //by zhangyan 收款同步到进销存，然后保存本地
            //如果是线上支付则不需要同步，只有ec后台增加或减少才会需要,如果类型为信用额则不需要同步
            if ($advance_type == '1'  && $paymethod != 'desposit') {    //|| isset($paymethod)
                $params = array(
                    'member_id'=>$member_id,
                    'money'=>0-$money,
                    'advance_type'=>$advance_type,
                    'bank_name'=>$bank_name,
                    'mtime'=>date("Y-m-d", time()),
                    'payment_id'=>$payment_id,
                    'order_id'=>$order_id,
                    'paymethod'=>$paymethod,
                    'memo'=>$memo,
                );
                //2015-9-16 by 张艳,在保存前，先同步到jxc,同步成功后才保存到本地
                $obj_order_create = kernel::single("b2c_order_pay");
                $r=$obj_order_create->_get_data_pay($params);

                if($r['rsp']===false) {
                    // $this->end(false, $r['data']['msg']);
                    $msg = app::get('ectools')->_('支付单生成失败！'.$r['data']['msg']);
                    return false;
                }
            }

            if($this->save($data)){
				/** 监听预存款变化 **/
				foreach(kernel::servicelist('member_advance_listener') as $service)
				{
					$arr_params = array(
						'member_id'=>$member_id,
						'doadd'=>false,
						'is_frontend'=>($is_frontend) ? true : false,
					);
					$service->listener_advance($arr_params);
				}
                return true;
            }else{
                $errMsg .= app::get('b2c')->_('更新预存款帐户失败');
                return false;
            }
        }else{
            return false;
        }

    }

    /**
     * @desc ：得到客户的信用额度信息
     * @author jeff #TM_TH_DTTM
     * @param 参数类型
     * @return 返回值类型
    */
    function get_xinyong($member_id) {
        // return $member_id;
        $t_credit = 0;//客户总信用额度
        $total_credit=0;//可用信用额度
        $total_real=0;//实际预存款
        $temp_yck=0;//可用额度的总消费
        
        $items_adv = $this->get_list_bymemId($member_id);
        // return $items_adv;
        // $count = count($items_adv);
        //items_adv=实际预存和信用额度预存的收入支出明细
        foreach ($items_adv as $keyadv => $adv) {
            if ($adv['advance_type']== '0') {//信用额度的充值汇总
                $tmp_advance=$adv['import_money']-$adv['explode_money'];
                $total_credit +=$tmp_advance;
            }elseif($adv['advance_type']== '1'){//实际预存充值汇总
                $tmp_real=$adv['import_money']-$adv['explode_money'];
                $total_real +=$tmp_real;
            }
            //添加预存款支付总金额
            if($adv['advance_type']=='2'){
                //订单用可用额度支付
                $temp_yc=$adv['explode_money']-$adv['import_money'];
                $temp_yck+= $temp_yc;
            }
        }

        $t_credit = $total_credit;
        if($total_real>0){
            if($temp_yck>$total_real){//如果总支出>实际预存，说明使用了信用支付
                $total_credit=$total_credit-($temp_yck-$total_real);
                $total_real=0;
            }else{//只使用了实际预存部分，信用额度保持初始值,且有实际余额
                $total_real=$total_real-$temp_yck;
            }
        }else{//实际预存款=0,可用额度=所有充值-所有消费
            $total_real=0;
            $total_credit=$total_credit-$temp_yck;
        }
        return array(
            'credit_total'=>$t_credit,//客户总信用额度
            'credit_active'=>$total_credit,//可用信用额度
            'deposit'=>$total_real,//实际预存款,所有预存之和
            'money_use'=>$temp_yck,//可用额度消费总额
        );
        
    }

    /**
     * getListByMemId 取得现有预存款充值记录
     *
     * @param mixed $member_id
     * @access public
     * @return void
     */
    function get_list_bymemId($member_id){
        return $this->getList('*',array('member_id'=>$member_id));
    }
    /**
     * get 取得现有预存款
     *
     * @param mixed $member_id
     * @access public
     * @return void
     */
    function get($member_id){
        $member = $this->app->model('members');
        $result = $member->dump($member_id);
        $advance=$result['advance']['total'];
        return $advance;
    }

    /**
     * get_shop_advance 取得现有预存款
     *
     * @param null
     * @access public
     * @return int
    */
    public function get_shop_advance(){
        $row = $this->getList('shop_advance',array(),0,1,'log_id DESC');
        if(!$row[0]) return 0;
        return $row[0]['shop_advance'];
    }

    function adj_amount($nMemberId,$aAdvanceInfo,&$errMsg='',$is_frontend=true){
    	$user = kernel::single('desktop_user');
    	$username = $user->user_data['account']['login_name'];
        $advance = $aAdvanceInfo['modify_advance'];
        $advance_type = $aAdvanceInfo['modify_advance_type'];
        $bank_name = $aAdvanceInfo['modify_bank_name'];
        $paymethod = '预存款';
        if(!$advance) return ;
        $memo = $aAdvanceInfo['modify_memo'];
        $operator = substr($advance,0,1);
        $operand = substr($advance,0);
        //by zhangyan 2015-10-28 添加$bank_name
        if($operator == '-' && is_numeric($operand) ){
            $message = $username.app::get('b2c')->_('管理员后台扣款');
            return $this->deduct($nMemberId,-$advance,$advance_type,$message,$errMsg, $payment_id='', $order_id='' ,$paymethod,$memo,$is_frontend,$bank_name);
        }elseif(is_numeric($operand)){
        	$message = $username.app::get('b2c')->_('管理员代充值');
            return $this->add($nMemberId,$advance,$advance_type,$message,$errMsg, $payment_id='', $order_id='' ,$paymethod,$memo,$type=0,$is_frontend,$bank_name);

        }
    }

    /**
     * fireEvent 触发事件
     *
     * @param mixed $event
     * @access public
     * @return void
     */
    function fireEvent($action , &$object, $member_id=0){
         $trigger = $this->app->model('trigger');
         return $trigger->object_fire_event($action,$object, $member_id,$this);
    }
//获取mac地址
    function GetMacAddr($os_type){
         switch ( strtolower($os_type) ){
              case "linux":
                    $this->forLinux();
                    break;
              case "solaris":
                    break;
              case "unix":
                    break;
              case "aix":
                    break;
              default:
                    $this->forWindows();
                    break;
          }
        $temp_array = array();
        foreach ( $this->return_array as $value ){
            if (preg_match("/[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f]/i",$value,$temp_array ) ){
             $this->mac_addr = $temp_array[0];
             break;
           }
        }
      unset($temp_array);
      return $this->mac_addr;
     }

     function forWindows(){
          @exec("ipconfig /all", $this->return_array);
          if ( $this->return_array )
                   return $this->return_array;
          else{
                   $ipconfig = $_SERVER["WINDIR"]."\system32\ipconfig.exe";
                   if ( is_file($ipconfig) )
                      @exec($ipconfig." /all", $this->return_array);
                   else
                      @exec($_SERVER["WINDIR"]."\system\ipconfig.exe /all", $this->return_array);
                   return $this->return_array;
          }
     }

     function forLinux(){
          @exec("ifconfig -a", $this->return_array);
          return $this->return_array;
     }
}
?>
